<template>
  <div class="app-container">
    <el-form class="searchForm" :inline="true" size="mini" ref="searchForm" :model="searchForm" label-width="80px">
      <el-form-item label="手册标题">
        <el-input v-model="searchForm.title" placeholder="请输入手册标题" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="doSearch">搜索</el-button>
        <el-button type="default" size="mini" icon="el-icon-refresh" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="searchs-content">
      <el-button v-permission="['applet:help:add']" type="primary" size="mini" plain icon="el-icon-plus"
        @click="addDialog">新增</el-button>
    </div>
    <Table :tableHeader="tableHeader" :tableData="tableData" :tableLoading="listLoading">
      <template slot="curstatus" slot-scope="scope">
        <div class="codes">
          <el-tag type="success" v-if="scope.row.isEnable === 1">启用</el-tag>
          <el-tag type="danger" v-else-if="scope.row.isEnable === 0">停用</el-tag>
        </div>
      </template>
      <template slot="action" slot-scope="scope">
        <el-button size="mini" @click="handleReview(scope.row)">预览</el-button>
        <el-button type="primary" size="mini" @click="addDialog(scope.row)"
          v-permission="['applet:help:edit']">编辑</el-button>
        <el-button v-permission="['applet:help:switch']" type="warning" size="mini" v-if="scope.row.isEnable === 1"
          @click="handleEnable(scope.row)">停用</el-button>
        <el-button v-permission="['applet:help:switch']" type="success" size="mini" v-else-if="scope.row.isEnable === 0"
          @click="handleEnable(scope.row)">启用</el-button>
        <el-button type="danger" size="mini" @click="handleDelete(scope.row)"
          v-permission="['applet:help:delete']">删除</el-button>
      </template>
    </Table>
    <pagination v-if="total > 0" :total="total" :page.sync="searchForm.pageNum" :limit.sync="searchForm.pageSize"
      @pagination="fetchData" />

    <!-- 弹框 -->
    <Dialog :visible="visible" width="32%" :loading="dialogBtnLoading" :title="dialogTitle" @confirmDialog="confirmDialog"
      @cancelDialog="cancelDialog">
      <el-form ref="dialogForm" :model="dialogForm" label-width="80px" :rules="dialogRules" class="dialogForm" size="small">
        <el-form-item label="手册标题" prop="title">
          <el-input class="ipt" v-model="dialogForm.title" clearable placeholder="请输入手册标题" />
        </el-form-item>
        <el-form-item label="设备分类" prop="equipClassify">
          <el-select class="ipt" v-model="dialogForm.equipClassify" placeholder="请选择设备分类" @change="equipChange" disabled>
            <el-option v-for="item in enums.EQUIP_CLASSIFY" :key="item.code" :label="item.label" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select :disabled="!dialogForm.equipClassify" class="ipt" v-model="dialogForm.equipTypeCode" clearable
            placeholder="请选择设备类型">
            <el-option v-for="item in equipTypeOption" :key="item.code" :label="item.name" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="厂商">
          <el-select @change="organizeChange" class="ipt" v-model="dialogForm.organizationId" placeholder="请选择厂商" clearable>
            <el-option v-for="item in factureOption" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运营商">
          <el-select class="ipt" :disabled="!dialogForm.organizationId" v-model="dialogForm.operatorId" clearable
            placeholder="请选择运营商">
            <el-option v-for="item in operatorOption" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="isEnable">
          <el-select class="ipt" v-model="dialogForm.isEnable" placeholder="请选择状态" clearable>
            <el-option v-for="item in enums.IS_ENABLE" :key="item.code" :label="item.label" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="手册上传" prop="url">
          <el-upload class="avatar-uploader" action="#" accept=".pdf, .doc, .docx,.jpg,.jpeg,.png"
            :http-request="uploadRequest" :file-list="fileList" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload" v-loading.fullscreen.lock="uploading" element-loading-text="拼命上传中"
            element-loading-spinner="el-icon-loading" element-loading-background="rgba(0,0,0,0.1)">
            <div slot="tip" class="el-upload__tip">
              只能上传word、pdf、jpg、png格式的文件，且大小不能超过2M！
            </div>
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import { equipment, operator } from "@/api/factuer";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";

import { handleConfirm } from "@/utils/messageBox";
import { removeNullUndefined } from "@/utils/index.js";

import { mapGetters } from "vuex";

export default {
  components: { Pagination, Table, Dialog },
  data() {
    return {
      listLoading: true,
      total: 0,
      searchForm: {
        pageNum: 1,
        pageSize: 15,
        title: "",
      },

      tableHeader: [
        {
          type: "index",
          label: "序号",
          width: "60",
          fixed: true,
        },
        {
          label: "手册标题",
          prop: "title",
        },
        {
          label: "厂商",
          prop: "organizationName",
        },
        {
          label: "设备类型",
          prop: "equipTypeName",
        },
        { slot: "curstatus", label: "状态" },
        {
          label: "修改时间",
          prop: "updateTime",
        },
        { slot: "action", label: "操作", width: "300" },
      ],
      tableData: [],
      visible: false, //弹框标识
      dialogForm: {
        title: "",
        equipClassify: "",
        equipTypeCode: "",
        operatorId: "",
        organizationId: "",
        isEnable: 0,
        url: "",
        originalFilename: "",
      },
      dialogRules: {
        title: [{ required: true, message: "请输入广告标题", trigger: "blur" }],
        organizationId: [
          { required: true, message: "请选择厂商", trigger: "change" },
        ],
        operatorId: [
          { required: true, message: "请选择运营商", trigger: "change" },
        ],
        isEnable: [
          { required: true, message: "请选择状态", trigger: "change" },
        ],
        equipClassify: [
          { required: true, message: "请选择设备分类", trigger: "change" },
        ],
        equipTypeCode: [
          { required: true, message: "请选择设备类型", trigger: "change" },
        ],
        url: [
          { required: true, message: "请上传开屏广告图片", trigger: "change" },
        ],
      },
      dialogTitle: "",

      dialogBtnLoading: false,

      factureOption: [], //运营商
      uploading: false,
      typeOption: [],
      equipTypeOption: [],
      operatorOption: [], //运营商option
      currentRow: {},
      fileList: [],
      fileUrl: "",
      IMGLink: this.IMGLink,
    };
  },

  created() {
    this.fetchData();
  },

  computed: {
        ...mapGetters(["enums", "equipTypeCode"]),
  },

  methods: {
    fetchData(val) {
      this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
      this.listLoading = true;
      this.tableData = [];
      this.total = 0;
      equipment(
        "/mg/list",
        "post",
        { ...removeNullUndefined(this.searchForm) },
        2
      )
        .then((res) => {
          this.tableData = res.data;
          this.total = +res.total;

          this.searchForm.pageNum = +res.pageNum;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },

    // 弹框取消
    cancelDialog() {
      this.visible = false;
      this.clearData();
      this.resetDialogForm("dialogForm");
    },
    clearData() {
      this.dialogForm = {
        title: "",
        equipClassify: "",
        equipTypeCode: "",
        operatorId: "",
        organizationId: "",
        isEnable: 0,
        url: "",
        originalFilename: "",
      };
      this.fileList = [];
    },
    // 弹框确认
    confirmDialog() {
      this.submitDialogForm("dialogForm");
    },
    async organizeChange(e) {
      this.operatorOption = [];
      this.dialogForm.operatorId = "";
      if(e){
      let datas = await operator("/all", "get", { organizationId: e });
      this.operatorOption = datas.data;
      }
    },
    // 新增
    async addDialog(row) {
      this.visible = true;
      if (this.factureOption.length == 0) {
        this.factureOption = await this.$store.dispatch(
          "operator/generatorFactuer"
        );
      }

      if (this.typeOption.length == 0) {
        this.typeOption = await this.$store.dispatch(
          "operator/generatorEquipType"
        );
      }

      this.equipChange(this.equipTypeCode);

      if (row.id) {
        this.dialogTitle = "编辑";
        this.currentRow = { ...row };
        let {
          title,
          equipClassify,
          equipTypeCode,
          operatorId,
          organizationId,
          isEnable,
          url,
          originalFilename,
        } = row;
        this.dialogForm = {
          title,
          equipClassify,
          equipTypeCode,
          operatorId,
          organizationId,
          isEnable,
          url,
          originalFilename,
        };
        this.fileList = [{ name: originalFilename, url: url }];

        this.equipTypeOption = this.typeOption.filter(
          (item) => item.equipClassify == equipClassify
        );
        if (organizationId) {
          const datas = await operator("/all", "get", {
            organizationId: organizationId,
          });
          this.operatorOption = datas.data;
        }
      } else {
        this.dialogTitle = "新增";
        this.currentRow = {};
        this.fileList = [];

        this.dialogForm.equipClassify = this.equipTypeCode;
      }
    },
    handleReview(row) {
      this.fileUrl = this.IMGLink + row.url;
      if (row.url) {
        if (row.url.includes(".doc") || row.url.includes(".docx")) {
          window.open(
            "https://view.officeapps.live.com/op/embed.aspx?src=" + this.fileUrl
          );
        } else {
          window.open(this.fileUrl);
        }
      } else {
        this.$message.warning("暂无文件");
      }
    },
    handleDelete(row) {
      handleConfirm("删除后不可恢复，确定继续？", "warning", "提示")
        .then((res) => {
          this.doDelete(row);
        })
        .catch((err) => { });
    },
    doDelete(row) {
      equipment(`/mg/delete/${row.id}`, "post").then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.fetchData();
        }
      });
    },
    handleEnable(row) {
      let msg = row.isEnable == 1 ? "停用" : "启用";
      handleConfirm(`确定要${msg}吗？`, "warning", "提示")
        .then((res) => {
          this.doEnable(row);
        })
        .catch((err) => { });
    },
    doEnable(row) {
      let status = row.isEnable == 1 ? 0 : 1;
      equipment(`/mg/update/enable/${row.id}`, "post", {
        isEnable: status,
      }).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.fetchData();
        }
      });
    },
    submitDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let msg = this.currentRow.id ? "编辑" : "新增";
          handleConfirm(`确定要${msg}吗？`, "warning", "提示")
            .then((res) => {
              this.doAdd();
            })
            .catch((err) => { });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetDialogForm(formName) {
      this.$refs[formName].resetFields();
    },

    resetSearch() {
      this.searchForm = {
        pageNum: this.searchForm.pageNum,
        pageSize: this.searchForm.pageSize,
        searchForm: "",
      };
    },
    doSearch() {
      this.searchForm.pageNum = 1;
      this.fetchData();
    },

    doAdd() {
      this.dialogBtnLoading = true;
      let url = this.currentRow.id
        ? `/mg/update/${this.currentRow.id}`
        : "/mg/insert";
      equipment(url, "post", this.dialogForm, 1)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.visible = false;
            this.fetchData();
          }
        })
        .finally(() => {
          this.dialogBtnLoading = false;
        });
    },
    uploadRequest(file) {
      //自定义上传
      let formData = new FormData();
      formData.append("file", file.file);

      this.uploading = true;
      equipment("/mg/upload", "post", formData, 1)
        .then((res) => {
          if (res.code == 200) {
            const { data } = res;
            this.dialogForm.url = data.fileUrl;
            this.dialogForm.originalFilename = data.originalFilename;
            this.fileList = [
              { name: data.originalFilename, url: data.fileUrl },
            ];
          } else {
            this.fileList = [];
          }
        })
        .finally(() => {
          this.uploading = false;
        })
        .catch(() => {
          this.fileList = [];
        });
    },
    handleAvatarSuccess(res, file) { },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("文件大小不能超过 2MB!");
      }
      return isLt2M;
    },
    equipChange(e) {
      this.dialogForm.equipTypeCode = "";
      this.equipTypeOption = this.typeOption.filter(
        (item) => item.equipClassify == e
      );
    },
  },
};
</script>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style lang="scss" scoped>
@import "@/styles/common.scss";
.searchForm {
    .el-form-item {
        margin-bottom: 8px;
    }
}
.ipt {
  width: 94%;
}

.tools {
  @include flexLayout(center, center);
  margin-top: -20px;

  .page {
    margin-right: 20px;
  }
}
.dialogForm{
  .el-form-item{
    margin-bottom:16px;
  }
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #333333;
}
</style>
